package hos.intent;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title: SettingIntent </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2024-03-20 20:19
 */
public class IntentCollection {

    //<editor-fold desc="MANUFACTURER">
    /**
     * Build.MANUFACTURER
     */
    protected static final String MANUFACTURER_HUAWEI = "HUAWEI";//华为

    protected static final String MANUFACTURER_MEIZU = "Meizu";//魅族

    protected static final String MANUFACTURER_XIAOMI = "Xiaomi";//小米

    protected static final String MANUFACTURER_SONY = "Sony";//索尼

    protected static final String MANUFACTURER_OPPO = "OPPO";//oppo

    protected static final String MANUFACTURER_LG = "LG";

    protected static final String MANUFACTURER_VIVO = "vivo";//vivo

    protected static final String MANUFACTURER_SAMSUNG = "samsung";//三星

    protected static final String MANUFACTURER_ZTE = "ZTE";//中兴

    protected static final String MANUFACTURER_YULONG = "YuLong";//酷派

    protected static final String MANUFACTURER_LENOVO = "LENOVO";//联想
    //</editor-fold>


    //<editor-fold desc="SettingAdapter">

    /**
     * 跳转到Huawei权限配置界面
     *
     * @param activity 上下文
     */

    private static Intent getHuaweiSetting(Context activity) {
        Intent intent = getIntent("com.meizu.safe.security.SHOW_APPSEC");
        intent.putExtra("packageName", activity.getPackageName());
        ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
        intent.setComponent(comp);
        return intent;
    }

    /**
     * 跳转到Meizu权限配置界面
     *
     * @param activity 上下文
     */

    private static Intent getMeizuSetting(Context activity) {
        Intent intent = getIntent("com.meizu.safe.security.SHOW_APPSEC");
        intent.putExtra("packageName", activity.getPackageName());
        return intent;
    }

    /**
     * 跳转到Xiaomi权限配置界面
     *
     * @param activity 上下文
     */

    private static Intent getXiaomiSetting(Context activity) {
        Intent intent = getIntent("miui.intent.action.APP_PERM_EDITOR");
        intent.putExtra("extra_pkgname", activity.getPackageName());
        ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
        intent.setComponent(componentName);
        return intent;
    }

    /**
     * 跳转到Sony权限配置界面
     *
     * @param activity 上下文
     */

    private static Intent getSonySetting(Context activity) {
        Intent intent = getIntent(Intent.ACTION_MAIN);
        intent.putExtra("packageName", activity.getPackageName());
        ComponentName comp = new ComponentName("com.sonymobile.cta", "com.sonymobile.cta.SomcCTAMainActivity");
        intent.setComponent(comp);
        return intent;
    }

    /**
     * 跳转到OPPO权限配置界面
     *
     * @param activity 上下文
     */

    private static Intent getOPPOSetting(Context activity) {
        Intent intent = getIntent(Intent.ACTION_MAIN);
        intent.putExtra("packageName", activity.getPackageName());
        ComponentName comp = new ComponentName("com.coloros.securitypermission", "com.coloros.securitypermission.permission.PermissionAppAllPermissionActivity");//R11t 7.1.1 os-v3.2
        intent.setComponent(comp);
        return intent;
    }

    /**
     * 跳转到LG权限配置界面
     *
     * @param activity 上下文
     */

    private static Intent getLGSetting(Context activity) {
        Intent intent = getIntent(Intent.ACTION_MAIN);
        intent.putExtra("packageName", activity.getPackageName());
        ComponentName comp = new ComponentName("com.android.settings",
                "com.android.settings.Settings$AccessLockSummaryActivity");
        intent.setComponent(comp);
        return intent;
    }

    /**
     * 默认打开应用详细页
     */
    public static Intent getAppSetting(Context context) {
        Intent intent = getIntent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        return intent;
    }

    /**
     * 跳转到应用设置界面
     *
     * @param activity 上下文
     * @return
     */
    public static Intent getSetting(Context activity) {
        Intent intent;
        switch (Build.MANUFACTURER) {
            case MANUFACTURER_HUAWEI:
                intent = getHuaweiSetting(activity);
                break;
            case MANUFACTURER_MEIZU:
                intent = getMeizuSetting(activity);
                break;
            case MANUFACTURER_XIAOMI:
                intent = getXiaomiSetting(activity);
                break;
            case MANUFACTURER_SONY:
                intent = getSonySetting(activity);
                break;
            case MANUFACTURER_OPPO:
                intent = getOPPOSetting(activity);
                break;
            case MANUFACTURER_LG:
                intent = getLGSetting(activity);
                break;
            default:
                Log.e("startSetting", "目前暂不支持此系统");
                intent = getAppSetting(activity);
        }
        return intent;
    }
    //</editor-fold>


    //<editor-fold desc="Setting">

    /**
     * 系统设置界面
     */
    public static Intent getSystemConfigSetting() {
        return getIntent(Settings.ACTION_SETTINGS);
    }

    /**
     * 通知意图
     *
     * @param context 上下文
     */
    public static Intent getNotificationSetting(Context context) {
        Intent intent = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent = getIntent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
        } else {
            intent = getSetting(context);
        }
        return intent;
    }

    /**
     * 安装意图
     *
     * @param context 上下文
     */
    public static Intent getInstallSetting(Context context) {
        Intent intent = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent = getIntent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        } else {
            intent = getSetting(context);
        }
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        return intent;
    }

    /**
     * 储存意图
     *
     * @param context 上下文
     */
    public static Intent getStorageSetting(Context context) {
        Intent intent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            intent = getIntent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        } else {
            intent = getSetting(context);
        }
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        if (intent.resolveActivity(context.getPackageManager()) == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                intent = getIntent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            }
        }
        return intent;
    }

    /**
     * 写入意图
     *
     * @param context 上下文
     */
    public static Intent getWriteSettings(Context context) {
        Intent intent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            intent = getIntent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        } else {
            intent = getSetting(context);
        }
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        return intent;
    }

    /**
     * 弹窗意图
     *
     * @param context 上下文
     */
    public static Intent getSystemAlertSetting(Context context) {
        Intent intent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            intent = getIntent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        } else {
            intent = getSetting(context);
        }
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        return intent;
    }

    /**
     * 跳转到定位设置页面
     */
    public static Intent getLocationSetting() {
        return getIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    }
    //</editor-fold>


    /**
     * 获取意图
     */
    public static Intent getIntent(String action) {
        Intent intent = new Intent(action);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        return intent;
    }

    /**
     * 跳转到目标页面，是否有返回值
     *
     * @param context 上下文
     * @param intent  意图
     */
    public static boolean startResult(Context context, Intent intent) {
        return startResult(context, intent, 99);
    }

    /**
     * 跳转到目标页面，是否有返回值
     *
     * @param context     上下文
     * @param intent      意图
     * @param requestCode 请求码
     * @return
     */
    public static boolean startResult(Context context, Intent intent, int requestCode) {
        try {
            if (!IntentAvailable.isIntentAvailable(context, intent)) {
                // 意图不可用
                return false;
            }
            if (context instanceof Activity) {
                ((Activity) context).startActivityForResult(intent, requestCode);
                return true;
            }
            // 是为了 使用applicaiton  context 启动activity 不会报错
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    //<editor-fold desc="Install">

    /**
     * 获取安装APK的意图
     *
     * @param uri 安装APK的URI
     */
    public static Intent getInstallAppIntent(final Uri uri) {
        if (uri == null) return null;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        intent.setDataAndType(uri, type);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        return intent;
    }

    /**
     * 卸载APK的意图
     *
     * @param pkgName 卸载apk的包名
     */
    public static Intent getUninstallAppIntent(final String pkgName) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:" + pkgName));
        return intent;
    }
    //</editor-fold>


    //<editor-fold desc="USE">


    /**
     * 获取需要启动的APK的意图
     *
     * @param context 上下文
     * @param pkgName 包名
     */
    public static Intent getLaunchAppIntent(Context context, final String pkgName) {
        String launcherActivity = getLauncherActivity(context, pkgName);
        if (launcherActivity == null || launcherActivity.isEmpty()) return null;
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClassName(pkgName, launcherActivity);
        return intent;
    }

    /**
     * 根据包名获取需要启动的APK
     *
     * @param context 上下文
     * @param pkg     包名
     */
    public static String getLauncherActivity(Context context, final String pkg) {
        if (pkg == null || pkg.isEmpty()) return "";
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(pkg);
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> info = pm.queryIntentActivities(intent, 0);
        if (info == null || info.size() == 0) {
            return "";
        }
        return info.get(0).activityInfo.name;
    }

    /**
     * 调用拨号面板
     *
     * @param phoneNumber 电话号码
     */
    public static Intent getDialIntent(String phoneNumber) {
        return new Intent(Intent.ACTION_DIAL,
                Uri.parse("tel:" + Uri.encode(phoneNumber)));
    }

    /**
     * 打电话
     *
     * @param phoneNumber 电话号码
     */
    public static Intent getCallIntent(final String phoneNumber) {
        return new Intent(Intent.ACTION_CALL,
                Uri.parse("tel:" + Uri.encode(phoneNumber)));
    }

    /**
     * 发送短信
     *
     * @param phoneNumber 电话号码
     * @param content     短信内容
     */
    public static Intent getSendSmsIntent(final String phoneNumber, final String content) {
        Uri uri = Uri.parse("smsto:" + Uri.encode(phoneNumber));
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        intent.putExtra("sms_body", content);
        return intent;
    }

    /**
     * 浏览器
     *
     * @param url 访问地址
     */
    public static Intent getUrl(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        //这个目的是为了 防止在部分机型上面 拉不起浏览器，，比说华为
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        return intent;
    }

    /**
     * 应用市场
     *
     * @param packageName 目标应用
     */
    public static Intent getMarket(String packageName) {
        return new Intent(Intent.ACTION_VIEW,
                Uri.parse("market://details?id=" + packageName));
    }


    //</editor-fold>

    //<editor-fold desc="Share">

    /**
     * 分享文字
     *
     * @param content 内容
     */
    public static Intent getShareTextIntent(final String content) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, content);
        return Intent.createChooser(intent, "");
    }

    /**
     * 分享图片
     *
     * @param imageUri 图片地址
     */
    public static Intent getShareTextImageIntent(final Uri imageUri) {
        return getShareTextImageIntent("", imageUri);
    }

    /**
     * 分享文字和图片
     *
     * @param content  内容
     * @param imageUri 图片地址
     */
    public static Intent getShareTextImageIntent(final String content, final Uri imageUri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TEXT, content);
        intent.putExtra(Intent.EXTRA_STREAM, imageUri);
        intent.setType("image/*");
        return Intent.createChooser(intent, "");
    }

    /**
     * 分享文字和图片
     *
     * @param content 内容
     * @param uris    图片地址列表
     */
    public static Intent getShareTextImageIntent(final String content, final ArrayList<Uri> uris) {
        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        intent.putExtra(Intent.EXTRA_TEXT, content);
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        intent.setType("image/*");
        return Intent.createChooser(intent, "");
    }
    //</editor-fold>

    //<editor-fold desc="File">
    public static Intent getFileIntent(Uri uri, String type) {
        Intent intent = getIntent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 23) {
            // 加入读取权限
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, type);
        return intent;
    }

    public static Intent getFileIntent(Context context, String pkgName, Uri uri, String type) {
        String launcherActivity = getLauncherActivity(context, pkgName);
        Intent intent = getFileIntent(uri, type);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClassName(pkgName, launcherActivity);
        return intent;
    }
    //</editor-fold>

    //<editor-fold desc="Media">

    /**
     * 媒体意图
     *
     * @param action 行为
     * @param uri    访问地址
     */
    public static Intent getMediaIntent(String action, Uri uri) {
        Intent intent = getIntent(action);
        // android11以后强制分区存储，外部资源无法访问，所以添加一个输出保存位置，然后取值操作G
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        return intent;
    }

    /**
     * 拍照意图
     *
     * @param uri 访问地址
     */
    public static Intent getImageMedia(Uri uri) {
        return getMediaIntent(MediaStore.ACTION_IMAGE_CAPTURE, uri);
    }

    /**
     * 录像意图
     *
     * @param uri 访问地址
     */
    public static Intent getVideoMedia(Uri uri) {
        return getMediaIntent(MediaStore.ACTION_VIDEO_CAPTURE, uri);
    }

    /**
     * 录音意图
     *
     * @param uri 访问地址
     */
    public static Intent getAudioMedia(Uri uri) {
        return getMediaIntent(MediaStore.Audio.Media.RECORD_SOUND_ACTION, uri);
    }

    /**
     * 相册意图
     */
    public static Intent getPickMedia(String type) {
        return new Intent(Intent.ACTION_PICK).setType(type);
    }

    /**
     * 相册意图
     */
    public static Intent getImagePickMedia() {
        return getPickMedia("image/*");
    }

    /**
     * 相册意图
     */
    public static Intent getVideoPickMedia() {
        return getPickMedia("video/*");
    }

    /**
     * 联系人意图
     */
    public static Intent getContacts() {
        return new Intent(Intent.ACTION_PICK).setType(ContactsContract.Contacts.CONTENT_TYPE);
    }

    /**
     * 裁剪意图
     */
    public static Intent getCrop(Uri inputUri, Uri outputUri) {
        return getCrop(inputUri, outputUri, 1, 1, 150, 150);
    }

    /**
     * 裁剪意图
     */
    public static Intent getCrop(Uri inputUri, Uri outputUri, int outputX, int outputY) {
        return getCrop(inputUri, outputUri, 1, 1, outputX, outputY);
    }

    /**
     * 裁剪意图
     */
    public static Intent getCrop(Uri inputUri, Uri outputUri,
                                 int aspectX, int aspectY,
                                 int outputX, int outputY) {
        Intent intent = getMediaIntent("com.android.camera.action.CROP", outputUri);
        intent.setDataAndType(inputUri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        // 图片格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        return intent;
    }
    //</editor-fold>

    //<editor-fold desc="Content">

    /**
     * 单选
     *
     * @param type 文件的类型
     */
    public static Intent getContentIntent(String type) {
        if (type == null || type.isEmpty()) {
            type = "*/*";
        }
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // android11以后强制分区存储，外部资源无法访问，所以添加一个输出保存位置，然后取值操作G
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        return intent.addCategory(Intent.CATEGORY_OPENABLE)
                .setType(type);
    }

    /**
     * 多选
     *
     * @param type 文件的类型
     */
    public static Intent getContentListIntent(String type) {
        if (type == null || type.isEmpty()) {
            type = "*/*";
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return getContentIntent(type)
                    .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        } else {
            return getContentIntent(type);
        }
    }
    //</editor-fold>

    //<editor-fold desc="Document">

    /**
     * 单选
     *
     * @param type 文件的类型
     */
    public static Intent getDocumentIntent(String... type) {
        if (type == null || type.length == 0) {
            type = new String[]{"*/*"};
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            // android11以后强制分区存储，外部资源无法访问，所以添加一个输出保存位置，然后取值操作G
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            return intent.putExtra(Intent.EXTRA_MIME_TYPES, type)
                    .setType("*/*");
        } else {
            return getContentIntent(type[0]);
        }
    }

    /**
     * 多选
     *
     * @param type 文件的类型
     */
    public static Intent getDocumentListIntent(String... type) {
        if (type == null || type.length == 0) {
            type = new String[]{"*/*"};
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            // android11以后强制分区存储，外部资源无法访问，所以添加一个输出保存位置，然后取值操作G
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            return getDocumentIntent(type)
                    .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        } else {
            return getContentListIntent(type[0]);
        }
    }
    //</editor-fold>
}
